package ajaxjs.admin.entry;
import java.sql.Connection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import ajaxjs.Util;
import ajaxjs.service.BaseServlet;
import ajaxjs.sql.DAO;

/**
 * CRUD
 * @author frank
 *
 */
public class CRUD extends DAO{
	public CRUD(Connection jdbcConn) {
		super(jdbcConn);
	}
	
	public String getTableName(){
		throw new NullPointerException("没有表名！Override me!" );
//		return null;
	}

	public int update(String pairs, int id){
		String sql = "UPDATE {tableName} SET {pairs} WHERE id = {id}";
		sql = sql.replace("{tableName}", getTableName());
		sql = sql.replace("{pairs}", pairs);
		sql = sql.replace("{id}", Integer.toString(id));
		
		System.out.println("update sql:::::::::" + sql);
		
		return executeUpdate(sql);	
	}
	public int update(String[] pairs, int id){
		return update(Util.stringJoin(pairs, ", "), id);	
	}
	
	public int update(Map<String, String> rawPairs, int id){
		if(rawPairs.size() == 0){
			throw new NullPointerException("No put params!");
		}
		
		String [] pairs = new String[rawPairs.size()];
		
		int i = 0;
		for(String fieldName : rawPairs.keySet()){
			String valueStr = rawPairs.get(fieldName);
			
			Object value = autoTypeDectect(valueStr);
			if(value instanceof Integer){
				pairs[i++] = fieldName + " = " + Integer.toString((Integer)value);
			}else{
				// String
				pairs[i++] = fieldName + " = '" + value.toString() + "'"; 
			}
		}
		return update(pairs, id);	
	}
	public int create(String[] columns, String[] values){
		 String sql = "INSERT INTO {tableName} ({columns}) VALUES ({values})";
		 sql = sql.replace("{tableName}", getTableName());
		 sql = sql.replace("{columns}", Util.stringJoin(columns, ", "));
		 sql = sql.replace("{values}", Util.stringJoin(values, ", "));
		
		 return executeUpdate(sql);	
	}
	
	private static Object autoTypeDectect(String value){
		int int_value = 0;
		Integer Int_value = 0;

		try{
			int_value = Integer.parseInt(value);
			Int_value = (Integer)int_value;
		}catch(NumberFormatException e){
			return value;
		}
		
		if(Int_value.toString().equals(value)){
			return (Integer)int_value;
		}else{
			return value;
		}
	}
	
	public Map<String, String> getPutRequest(HttpServletRequest request){
		return fixPut.getPutRequest(request);
	}
	public String getPutRequest(HttpServletRequest request, String key){
		return fixPut.getPutRequest(request, key);
	}
	
	/**
	 * 选择满足条件的最后一条记录
	 * @return
	 */
	public static Integer getMaxId(String tableName, String where){
		DAO dao = new DAO(BaseServlet.getConnStr());
		String sql = "SELECT max(id) AS id FROM " + tableName;
		if(where != null){
			sql += " WHERE " + where;
		}
		return (Integer)dao.query(sql, true, null);
	}
	
	public static Integer getMaxId(String tableName){
		return getMaxId(tableName, null);
	}
}
